package com.one.rope.mvp.basecore.third.wx.official;

import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.one.rope.mvp.basecore.third.wx.common.*;
import com.one.rope.mvp.basecore.third.wx.miniprogram.WxConstant;
import com.one.rope.mvp.basecore.util.DateUtil;
import com.one.rope.mvp.basecore.util.HttpRequestUtil;
import com.one.rope.mvp.basecore.util.JsonUtils;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;

/**
 * <p>
 * 微信公众号相关操作工具类
 * <p>
 *
 * @author ： Weijian.Liu
 * @date ： 2020/3/23 22:44
 */
@Slf4j
public class WxOfficeUtil {

  private static final String getAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token";
  private static final String createQrcodeUrl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=";
  private static final String grantType = "client_credential";
  // 二维码类型 QR_SCENE为临时的整型参数值，QR_STR_SCENE为临时的字符串参数值，
  // QR_LIMIT_SCENE为永久的整型参数值，QR_LIMIT_STR_SCENE为永久的字符串参数值
  private static final String ACTION_NAME = "QR_LIMIT_STR_SCENE";

  // 获取二维码地址URL
  private static final String ticketUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=";
  // 获取公众号图片素材列表URL
  private static final String mediaListUrl = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=";
  // 发送客服消息请求url
  private static final String sendCustomMsgUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=";
  // 发送模板消息请求url
  private static final String sendTemplateMsgUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";
  // 获取用户基本信息url
  private static final String getUserInfoUrl = "https://api.weixin.qq.com/cgi-bin/user/info";

  private static final String color = "#173177";
  /**
   * 获取微信公众号access_token
   * @param appId
   * @param appSecret
   * @return
   */
  public static String getAccessToken(String appId, String appSecret) throws Exception{
    Map<String, String> param = new HashMap<>();
    param.put("grant_type", grantType);
    param.put("appid", appId);
    param.put("secret", appSecret);
    String response = HttpRequestUtil.sendGetRequest(getAccessTokenUrl, param);
    log.info("获取公众号access_token: {}", response);
    Map<String, String> resMap = JsonUtils.stringToMap(response);
    if(null == resMap || null != resMap.get("errcode")){
      log.error("获取公众号access_token失败，原因: {}", resMap.get("errmsg"));
      throw new Exception();
    }
    return resMap.get("access_token");
  }

  /**
   * 创建永久二维码URL
   * @param accessToken
   * @param sceneStr
   * @return
   */
  public static String createQrcode(String accessToken, String sceneStr) throws Exception{
    JSONObject param = new JSONObject();
    param.put("action_name", ACTION_NAME);
    Map<String, Object> scene = new HashMap<>();
    Map<String, String> sceneStrMap = new HashMap<>();
    sceneStrMap.put("scene_str", sceneStr);
    scene.put("scene", sceneStrMap);
    param.put("action_info", JsonUtils.mapOjectToJsonString(scene));
    String response = HttpRequestUtil.sendPostRequest(createQrcodeUrl+accessToken, param);
    System.out.println(response);
    Map<String, String> resMap = JsonUtils.stringToMap(response);
    if(null == resMap || null != resMap.get("errcode")){
      log.error("创建二维码失败，原因: {}", resMap.get("errmsg"));
      throw new Exception();
    }
    return ticketUrl + resMap.get("ticket");
  }

  /**
   * 获取用户基本信息
   * @param accessToken
   * @param openId
   * @return
   */
  public static WxGetUserInfoRes getUserInfo(String accessToken, String openId) {
    // "&openid=" + openId + "&lang=zh_CN"
    Map<String, String> paramMap = new HashMap<>();
    paramMap.put("access_token", accessToken);
    paramMap.put("openid", openId);
    paramMap.put("lang", "zh_CN");
    String response = HttpRequestUtil.sendGetRequest(getUserInfoUrl, paramMap);
    log.info("获取公众号用户信息:{}", response);
    WxGetUserInfoRes userInfoRes = JsonUtils.jsonToObject(response, WxGetUserInfoRes.class);
    return userInfoRes;
  }
  /**
   * 获取素材列表
   * @param accessToken
   */
  public static void getMediaList(String accessToken){
    String url = mediaListUrl + accessToken;
    JSONObject param = new JSONObject();
    param.put("type", "image");
    param.put("offset", 0);
    param.put("count", 10);
    String response = HttpRequestUtil.sendPostRequest(url, param);
    log.info("获取素材列表: {}", response);
  }

  /**
   * 发送公众号客服文本消息
   * @param msgReq
   * @return
   */
  public static WxSendMsgRes sendCustomerTextMsg(WxSendCustomTextMsgReq msgReq){
    Map<String, Object> params = new HashMap<>();
    params.put("touser", msgReq.getToUser());
    params.put("msgtype", WxConstant.MSG_TYPE_TXT);
    Map<String, Object> txtMap = new HashMap<>();
    txtMap.put("content", msgReq.getContent());
    params.put("text", txtMap);
    String response = HttpRequestUtil.sendPostRequest(sendCustomMsgUrl + msgReq.getAccessToken(), JsonUtils.mapOjectToSfJson(params));
    WxSendMsgRes msgRes = JsonUtils.jsonToObject(response, WxSendMsgRes.class);
    return msgRes;
  }

  /**
   * 发送公众号模板文本消息
   * @param msgReq
   * @return
   */
  public static WxSendMsgRes sendTemplateTextMsg(WxSendTemplateMsgReq msgReq){
    Map<String, Object> params = new HashMap<>();
    params.put("touser", msgReq.getToUser());
    params.put("template_id", msgReq.getTemplateId());
    params.put("url", msgReq.getUrl());
    Map<String, String> miniprogram = new HashMap<>();
    miniprogram.put("appid", msgReq.getMiniprogram().getAppid());
    miniprogram.put("pagepath", msgReq.getMiniprogram().getPagepath());
    params.put("miniprogram", miniprogram);

    Map<String, Object> data = new HashMap<>();
    Map<String, String> first = new HashMap<>();
    first.put("value", msgReq.getMsgCotent().getFirst());
    first.put("color", color);
    data.put("first", first);

    Map<String, String> keyword1 = new HashMap<>();
    keyword1.put("value", msgReq.getMsgCotent().getKeyword1());
    keyword1.put("color", color);
    data.put("keyword1", keyword1);

    Map<String, String> keyword2 = new HashMap<>();
    keyword2.put("value", msgReq.getMsgCotent().getKeyword2());
    keyword2.put("color", color);
    data.put("keyword2", keyword2);

//    Map<String, String> remark = new HashMap<>();
//    remark.put("value", msgReq.getMsgCotent().getRemark());
//    remark.put("color", color);
//    data.put("remark", remark);

    params.put("data", data);
    String response = HttpRequestUtil.sendPostRequest(sendTemplateMsgUrl + msgReq.getAccessToken(), JsonUtils.mapOjectToSfJson(params));
    log.info("推送模板消息内容: " + JsonUtils.mapOjectToSfJson(params).toString());
    WxSendMsgRes msgRes = JsonUtils.jsonToObject(response, WxSendMsgRes.class);
    return msgRes;
  }

  public static void main(String[] args) throws Exception{
    WxSendTemplateMsgReq msgReq = new WxSendTemplateMsgReq();
    WxTemplateMsgCotent msgCotent = new WxTemplateMsgCotent();
    msgCotent.setFirst("测试");
    msgCotent.setKeyword1("\uD83D\uDC47");
    msgCotent.setKeyword2(DateUtil.dateToString(new Date()));
//    msgCotent.setRemark("空");
    msgReq.setMsgCotent(msgCotent);
    msgReq.setTemplateId("pNULTUNhktvolTOmwRZnQOEnnDMav-yjK9wA6Fr_HYI");
    msgReq.setUrl("http://www.duozhu.co/");
    WxMiniprogramVO miniprogramVO = new WxMiniprogramVO();
    miniprogramVO.setAppid("wx76e5abc630337e6d");
    miniprogramVO.setPagepath("pages/b_terminal/jj_detail/jj_detail?p_id=1252515300223426561&b_id=1251068428329914369");
    msgReq.setMiniprogram(miniprogramVO);
    msgReq.setAccessToken("32_o4t_mSGwWH0Bo47GecO5_rojFBPnQV66phTSIa-i72Z5jxvU0DwLdygt5iFEAmgg6Gjs5qre_-UraWdxnlgblUzpSy0T_YiAJB6aDPmdyiIFrs1c23tm3apITVat0dky_FCb0OFOmUtPrudTZMCcAGAUHX");
    msgReq.setToUser("oW4tdv8PvQ0n4LIn-wgvczCEjhik");
    System.out.println(sendTemplateTextMsg(msgReq));
//    try {
//      createQrcode("31_O3nS6EMMmDTiTPNo04OBQK1rbTavazyfkW9rqeMM9AtmdW6EKr2zaykoD_xdQEkFDkCgUKywLET2AjhSSPqKx3buf5lDAO6o9G6zJfwDtpJFI6z4TeXBPAX9eoxNkqg3vLH4t6eNpX7jbpHaPOBjAFAAZM", "user121");
//    }catch (Exception e){
//
//    }
//    getMediaList("31_HoLlFTFuRUxS1TrAxeBEpyMlaYYhepcQRAPPJn_QHulzkwhk0P7JN4b7XDbl-w7yUM6lyEqtU1V-EWwHMQU82oLSnuWBvLEnz8tAqczcnXi-OcN1_cCrOTaJfiyP8K-aZ1rgTx8qK6lM2GyOWPSaADAJCF");

//     getUserInfo("31_Vzj_wBZfSrYrxSmMelgMtviIJX76a9IAU3WB0j7yBhIjrjFJ2ePRe_90_A2MtGuOvE9TvmzlY4mFXSu4UskHeHLnptcMKphtLC2Q-s34sImHloRwZTmfifs6VmOA0R8WeIEcUgE6jfJCVu6BXPCiAHADVI", "oW4tdv4LfZwP5bQ7274FuuOO9a-s");
  }
}
